import { NextResponse } from "next/server";
import fs from "fs/promises";
import path from "path";

const infoPath = path.join(process.cwd(), "src/config/info.json");
let cache = null;

async function loadCache() {
  const data = await fs.readFile(infoPath, "utf-8");
  cache = JSON.parse(data);
}

export async function GET() {
  const codeMap = {0: '读取成功', 1: '读取失败'};
  try {
    if (!cache) {
      await loadCache();
    }
    return NextResponse.json({ code: 0, codeMap, message: "Reading success", data: cache });
  } catch (err) {
    return NextResponse.json({ code: 1, codeMap, message: "Reading failed", error: err.message }, { status: 500 });
  }
}

export async function PUT(request) {
  const codeMap = {0: '写入成功', 1: '写入失败'};
  try {
    const body = await request.json();
    await fs.writeFile(infoPath, JSON.stringify(body, null, 2), "utf-8");
    cache = body;
    return NextResponse.json({ code: 0, codeMap, message: "Change success" });
  } catch (err) {
    return NextResponse.json({ code: 1, codeMap, message: "Write failure", error: err.message }, { status: 500 });
  }
}